package com.chen.spikemall.repository;

import com.chen.spikemall.exception.NoInventoryException;
import com.chen.spikemall.redis.BlockingRedisLock;
import com.chen.spikemall.redis.RedisCommonComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class GoodsStoreValueRepository {

    private static final String STORE_COUNT_SUFFIX = "_store_count";

    @Autowired
    private RedisCommonComponent redisCommonComponent;

    public void setStoreCount(String goodsNo, final int storeCount) {
        redisCommonComponent.set(goodsNo + STORE_COUNT_SUFFIX, "" + storeCount);
    }

    public int decrStoreCount(final String goodsNo, final int decrNum) throws NoInventoryException {

        BlockingRedisLock redisLock = redisCommonComponent.newBlockingRedisLock(goodsNo);
        final String storeKey = goodsNo + STORE_COUNT_SUFFIX;

        int storeValue = 0;


        try {
            storeValue = Integer.valueOf(redisCommonComponent.get(storeKey));
        } catch (NumberFormatException e) {

        }
        if (storeValue == 0) {
            throw new NoInventoryException(goodsNo);
        }

        redisLock.lock();
        storeValue = Integer.valueOf(redisCommonComponent.get(storeKey));
        if (storeValue == 0) {
            redisLock.unlock();
            throw new NoInventoryException(goodsNo);
        }

        redisCommonComponent.decr(storeKey, decrNum);
        redisLock.unlock();

        return storeValue;
    }
}
